package com.iflytek.aidemo.student;

import android.content.Context;
import android.content.SharedPreferences;
import java.util.Calendar;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;

/**
 * 轻量存储：管理上周错题练习状态，仅保留当前周和上一周的数据。
 */
public class WrongPushStore {
    private static final String PREF = "wrong_push";
    private static final String KEY_PENDING = "pending";
    private static final String KEY_CLEARED_PREFIX = "cleared_week_";
    private static final String KEY_CLEARED_USER_PREFIX = "cleared_week_user_";
    private static final String KEY_LAST_WEEK = "last_week_key";

    public static void setPending(Context ctx, boolean pending) {
        SharedPreferences sp = ctx.getSharedPreferences(PREF, Context.MODE_PRIVATE);
        sp.edit().putBoolean(KEY_PENDING, pending).apply();
    }

    public static boolean hasPending(Context ctx) {
        SharedPreferences sp = ctx.getSharedPreferences(PREF, Context.MODE_PRIVATE);
        return sp.getBoolean(KEY_PENDING, false);
    }

    /** 返回形如 yyyy-ww 的周键（使用周一为一周起始，随 Calendar 本地规则）。 */
    public static String currentWeekKey() {
        return getWeekKeyFor(0);
    }

    /** 获取前n周的周键 */
    private static String getWeekKeyFor(int weeksAgo) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.WEEK_OF_YEAR, -weeksAgo);
        int year = cal.get(Calendar.YEAR);
        int week = cal.get(Calendar.WEEK_OF_YEAR);
        return year + "-" + week;
    }

    public static String getLastWeekKey() {
        return getWeekKeyFor(1);
    }

    /**
     * 用户维度：标记本周已处理（无论删除或保留），用于抑制基于时间的红点。
     * @param ctx 上下文
     * @param userId 用户ID，不能为空
     * @param weekKey 周键，格式为 yyyy-ww
     * @param cleared 是否已处理
     * @throws IllegalArgumentException 如果参数无效
     */
    public static void markClearedForWeek(Context ctx, String userId, String weekKey, boolean cleared) {
        if (ctx == null) {
            throw new IllegalArgumentException("Context cannot be null");
        }
        if (userId == null || userId.isEmpty()) {
            throw new IllegalArgumentException("User ID cannot be null or empty");
        }
        if (weekKey == null || weekKey.isEmpty()) {
            throw new IllegalArgumentException("Week key cannot be null or empty");
        }
        
        SharedPreferences sp = ctx.getSharedPreferences(PREF, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        
        // 使用用户ID作为键的一部分
        String key = KEY_CLEARED_USER_PREFIX + userId + "_" + weekKey;
        editor.putBoolean(key, cleared);
        
        // 保存最后一次处理的周（用于清理）
        editor.putString(KEY_LAST_WEEK, weekKey);
        
        // 清理旧数据
        cleanupOldWeeks(sp, weekKey);
        
        boolean commitResult = editor.commit();
        System.out.println("Marked week as " + (cleared ? "cleared" : "not cleared") + 
                         " for user " + userId + ", week " + weekKey + ", commit " + 
                         (commitResult ? "succeeded" : "failed"));
    }

    /**
     * 用户维度：是否已处理过指定周。
     * @param ctx 上下文
     * @param userId 用户ID，不能为空
     * @param weekKey 周键，格式为 yyyy-ww
     * @return 如果该用户该周已处理则返回true，否则返回false
     * @throws IllegalArgumentException 如果参数无效
     */
    public static boolean isClearedForWeek(Context ctx, String userId, String weekKey) {
        if (ctx == null) {
            throw new IllegalArgumentException("Context cannot be null");
        }
        if (userId == null || userId.isEmpty()) {
            throw new IllegalArgumentException("User ID cannot be null or empty");
        }
        if (weekKey == null || weekKey.isEmpty()) {
            throw new IllegalArgumentException("Week key cannot be null or empty");
        }
        
        // 使用 application context 避免内存泄漏
        Context appContext = ctx.getApplicationContext();
        SharedPreferences sp = appContext.getSharedPreferences(PREF, Context.MODE_PRIVATE);
        String prefKey = KEY_CLEARED_USER_PREFIX + userId + "_" + weekKey;

        
        boolean value = sp.getBoolean(prefKey, false);
        System.out.println("Reading cleared status - key: " + prefKey + ", value: " + value);
        return value;
    }


    /**
     * 清理除当前周和上一周之外的所有数据
     * @param sp SharedPreferences 实例
     * @param currentWeekKey 当前周键
     */
    private static void cleanupOldWeeks(SharedPreferences sp, String currentWeekKey) {
        if (sp == null || currentWeekKey == null) {
            return;
        }
        
        String lastWeekKey = getLastWeekKey();
        SharedPreferences.Editor editor = sp.edit();
        boolean hasChanges = false;
        
        // 获取所有键
        for (String key : sp.getAll().keySet()) {
            if (key.startsWith(KEY_CLEARED_USER_PREFIX)) {
                // 对于用户特定的键，格式为: cleared_week_user_<userId>_<weekKey>
                // 提取最后的 weekKey 部分
                String weekKey = "";
                try {
                    // 从完整键中提取周键部分
                    // 格式: cleared_week_user_<userId>_<weekKey>
                    int lastUnderscore = key.lastIndexOf('_');
                    int secondLastUnderscore = key.lastIndexOf('_', lastUnderscore - 1);
                    if (lastUnderscore > 0 && secondLastUnderscore > 0) {
                        weekKey = key.substring(secondLastUnderscore + 1);
                    }
                } catch (Exception e) {
                    System.err.println("Error parsing key: " + key + ", " + e.getMessage());
                    continue;
                }
                
                // 如果不是当前周或上一周的数据，则删除
                if (!weekKey.isEmpty() && !weekKey.startsWith(currentWeekKey) && !weekKey.startsWith(lastWeekKey)) {
                    System.out.println("Cleaning up old week data - key: " + key);
                    editor.remove(key);
                    hasChanges = true;
                }
            }
        }
        
        if (hasChanges) {
            boolean commitResult = editor.commit();
            System.out.println("Cleanup operation " + (commitResult ? "succeeded" : "failed"));
        }
    }
    
    /** 是否已过本周一09:00（用于按时间显示红点）。 */
    public static boolean isAfterThisMondayNine() {
        Calendar now = Calendar.getInstance();
        Calendar monday9 = Calendar.getInstance();
        
        // 设置为当天09:00:00
        monday9.set(Calendar.HOUR_OF_DAY, 9);
        monday9.set(Calendar.MINUTE, 0);
        monday9.set(Calendar.SECOND, 0);
        monday9.set(Calendar.MILLISECOND, 0);
        
        // 设置为本周一
        monday9.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        
        // 如果当前时间早于本周一09:00，则返回false
        return now.after(monday9);
    }
}
